<template>
  <div class="containerPage">
    <div class="breadcrumb">
      <div class="name">{{ routeName }}</div>
      <div class="btn">
        <el-button type="primary" :icon="Plus" @click="openSelectUser()">添加成员</el-button>
      </div>
    </div>
    <search-input placeholder="搜索姓名" @inputEnter="searchInputEnter">
      <!-- 角色 -->
      <div class="total_people">{{ requestStr.total }}个成员</div>
      <div class="type_box">
        <div class="type_item" @click="selectItem('all')" :class="{ selected: selectedItem === 'all' }">全部</div>
        <div class="type_item" @click="selectItem('edit')" :class="{ selected: selectedItem === 'edit' }">编辑
        </div>
        <el-popover ref="popover" :virtual-ref="buttonRef" trigger="click" placement="bottom" :width="200">
          <div class="more_list">
            <div class="more_item" @click="selectSubItem('manager')"
              :class="{ selected: selectedSubItem === 'manager' }">管理</div>
            <div class="more_item" @click="selectSubItem('read')" :class="{ selected: selectedSubItem === 'read' }">只读
            </div>
          </div>
        </el-popover>
        <div class="type_more" ref="buttonRef" :class="{ selected: selectedItem === 'more' }">
          <div>更多</div>
          <el-icon>
            <ArrowDown />
          </el-icon>
        </div>
      </div>
    </search-input>

    <div class="table_box">
      <el-table :data="TableData" class="tableClass" ref="multipleTable" tooltip-effect="dark" style="width: 100%"
        :highlight-selection-row="true" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" :selectable="selectableFunc"></el-table-column>
        <el-table-column label="姓名" prop="nickName" show-overflow-tooltip>
          <template v-if="isTableHeaderBtn" #header>
            <div style="height: 22px;padding-left: 0px;">
              <table-header-btn :tableRowArray="tableRowArray" @roleClick="onRoleClick"
                @deleteClick="delUser"></table-header-btn>
            </div>
          </template>
          <template #default="scope">
            <div>
              <span>{{ scope.row.nickName }}</span>
              <el-tag v-if="scope.row.userId == createBy" size="small" style="margin-left:5px">创建者</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="权限">
          <template v-if="isTableHeaderBtn" #header>
            <span>{{ `&nbsp;` }}</span>
          </template>
          <template #default="scope">
            {{ scope.row.permissionsName }}
          </template>
        </el-table-column>
        <el-table-column prop="detailsDescribe" label="权限描述">
          <template v-if="isTableHeaderBtn" #header>
            <span>{{ `&nbsp;` }}</span>
          </template>
          <template #default="scope">
            {{ scope.row.detailsDescribe }}
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-top: 5px;">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="requestStr.page" :page-sizes="[10, 20, 30, 40]" :page-size="requestStr.size"
          layout="total,  prev, pager, next,sizes" :total="requestStr.total">
        </el-pagination>
      </div>
    </div>
    <SelectUser ref="selectUserRef" @sureDialogTransferClick="sureDialogTransferClick" />
    <change-user-role :show-confirm-button="true" v-model="internalVisible" :title="dialogTitle"
      @close="dialogCloseColse" @confirm="dialogConfirm" type="form" class="change_user">
      <div v-if="tableRowArray.length === 1" class="tip_name">
        设置成员
        <p>{{ tableRowArray[0].nickName }}</p>
        在当前日历中的权限
      </div>
      <div v-else class="tip_name">
        设置
        <p>{{ tableRowArray.length }}</p>
        个成员在当前日历中的权限
      </div>

      <el-form ref="form" :model="formData">
        <el-form-item label="权限" prop="permissionsId">
          <el-select v-model="formData.permissionsId" placeholder="请选择权限">
            <el-option v-for="item in options" :key="item.permissionsId" :label="item.permissionsName"
              :value="item.permissionsId"> </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </change-user-role>
  </div>
</template>

<script lang="ts" setup>
import { Plus } from '@element-plus/icons-vue'
import SearchInput from "./components/search-input.vue"
import {
  sysScheduleGetDetail,
  apiSysScheduleGetPermission,
  apiSysScheduleUserAdd,
  apiSysScheduleUserEdit,
  apiSysScheduleUserDelete
} from '@/api/calendar'
import SelectUser from '../components/select-user-check/select-user.vue'
import tableHeaderBtn from './components/table-header-btn.vue'
import changeUserRole from './components/change-user-role.vue'

const router = useRouter()
const routeName = ref(router.currentRoute.value.meta.title)
const scheduleData = ref(JSON.parse(localStorage.getItem('scheduleData')) || {})
const taskUserid = ref('')
const selectedItem = ref('all')
const selectedSubItem = ref('')
const TableData = ref([])
const isTableHeaderBtn = ref(false)
const tableRowArray = ref([])
const createBy = ref(null)
const internalVisible = ref(false)
const dialogTitle = ref('')
const options = ref([{ permissionsId: 1, permissionsName: '权限一' },
{ permissionsId: 2, permissionsName: '权限二' },])
const inputString = ref('')
const permissionsId = ref(null)
const buttonRef = ref()
const popover = ref()
const selectUserRef = ref()
const formData = ref({
  permissionsId: null,
})



const requestStr = reactive({
  page: 1,
  size: 10,
  total: 0,
})



// 添加成员
const openSelectUser = () => {
  if (selectUserRef.value) {
    const clonedList = JSON.parse(JSON.stringify(TableData.value))
    selectUserRef.value.openDialogTransfer(clonedList)
  }
}

// 搜索成员
const searchInputEnter = (e: any) => {
  inputString.value = e
  getDatails()
}
// 选中
const selectItem = (item) => {
  selectedItem.value = item
  if (item === 'all') {
    permissionsId.value = ''
    getDatails()
  } else if (item === 'edit') {
    permissionsId.value = 2
    getDatails()
  }

}

const selectSubItem = (item) => {
  selectedItem.value = 'more'
  selectedSubItem.value = item
  if (item === 'manager') {
    permissionsId.value = 1
    getDatails()
  } else if (item === 'read') {
    permissionsId.value = 3
    getDatails()
  }
  // 隐藏 popover
  popover.value.hide()

}
// 多选
const handleSelectionChange = (val) => {
  tableRowArray.value = val
  if (val.length > 0) {
    isTableHeaderBtn.value = true
  } else {
    isTableHeaderBtn.value = false
  }
}

const selectableFunc = (row, index) => {
  return row.userId !== createBy.value
}

const onRoleClick = () => {
  internalVisible.value = true
  dialogTitle.value = '设置权限'
  if (tableRowArray.value.length > 1) {
    formData.value.permissionsId = 2
  } else {
    formData.value.permissionsId = tableRowArray.value[0].permissionsId
  }
}

const delUser = async () => {
  let ids = tableRowArray.value.map((item) => item.userId)
  let res = await apiSysScheduleUserDelete({
    scheduleId: scheduleData.value.id,
    userIds: ids
  })
  if (res.code == 200) {
    ElMessage.success('删除成功')
    getDatails()
  } else {
    ElMessage.error(res.msg)
  }
}
const sureDialogTransferClick = (data) => {
  let ids = data.map((item) => item.userId)
  apiSysScheduleUserAdd({
    scheduleId: scheduleData.value.id,
    userIds: ids,
    permissionsId: 2
  }).then((res) => {
    if (res.code == 200) {
      getDatails()
    } else {
      ElMessage.error(res.msg)
    }
  })
}
const dialogCloseColse = () => {
  internalVisible.value = false
}
const dialogConfirm = async () => {
  let ids = []
  tableRowArray.value.forEach((item) => {
    ids.push(item.userId)
  })
  if (ids.length > 0) {
    let res = await apiSysScheduleUserEdit({
      scheduleId: scheduleData.value.id,
      userIds: ids,
      permissionsId: formData.value.permissionsId
    })
    if (res.code == 200) {
      ElMessage.success('设置成功')
      internalVisible.value = false
      getDatails()
    }
  }
}
const handleSizeChange = (val) => {
  requestStr.size = val
  getDatails()
}
const handleCurrentChange = (val) => {
  requestStr.page = val
  getDatails()
}
const getPermissions = async () => {
  let res = await apiSysScheduleGetPermission()
  if (res.code == 200) {
    options.value = res.data
  }
}
const getDatails = async () => {
  const res = await sysScheduleGetDetail(scheduleData.value.id, requestStr.page - 1, requestStr.size, inputString.value, permissionsId.value)
  if (res.code == 200) {
    createBy.value = res.data.createBy
    TableData.value = res.data.userAuthorityPage.rows
    requestStr.total = res.data.userAuthorityPage.total
  }
}
getDatails()
getPermissions()
</script>
















<style lang="scss" scoped>
:deep(.more_item) {
  width: 100%;
  height: 30px;
  line-height: 30px;
  cursor: pointer;
  color: #333;
  font-size: 14px;

  &:hover {
    background-color: #f5f5f5;
    color: #333;
  }
}

:deep(.table_NameBox) {
  display: flex;
  align-items: center;

  .avatar {
    width: 24px;
    height: 24px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 12px;
    background-color: #56abfb;
    margin-right: 4px;

    span {
      transform: scale(0.9, 0.9);
    }
  }
}


.containerPage {
  width: 100%;
  height: 100%;

  .breadcrumb {
    border-bottom: 1px solid #eee;
    height: 51px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;

    .name {
      color: #333;
      padding-left: 20px;
    }

    .btn {
      padding-right: 40px;
    }
  }


  .type_box {
    flex: auto;
    display: flex;
    justify-content: flex-end;
    // align-items: center;

    .type_item {
      width: 54px;
      height: 28px;
      line-height: 28px;
      border-radius: 18px;
      margin-right: 20px;
      color: #666;
      background-color: #f5f5f5;
      text-align: center;
      font-size: 14px;
      cursor: pointer;
    }

    .type_more {
      display: flex;
      width: 74px;
      height: 28px;
      align-items: center;
      cursor: pointer;
      color: #666;
      background-color: #f5f5f5;
      font-size: 14px;
      justify-content: center;
      border-radius: 18px;

      .more_list {
        // display: none;
        width: 200px;
        height: 100px;
        background-color: #fff;
      }
    }

    .selected {
      background-color: rgba(102, 152, 255, 0.1);
      color: #6698ff;
      /* 选中的背景色 */
    }
  }


  .table_box {
    margin-left: 20px;

    .tableClass {
      border-color: rgba(0, 0, 0, 0);
    }

    .has-gutter {
      height: 50px !important;
    }

    th {
      color: #333;
      font-weight: normal;
    }

    tr {
      height: 50px;
    }

    .descending .sort-caret.descending {
      border-top-color: #6698ff;
    }

    .ascending .sort-caret.ascending {
      border-bottom-color: #6698ff;
    }

    td.el-table__cell {
      border-bottom: 1px solid #eee;
    }

    .el-table__body tr:hover .realName_box_right {
      visibility: visible;
    }
  }

  .change_user {
    .el-dialog__body {
      padding: 0px 20px;

      .el-select {
        width: 100%;
      }

      .tip_name {
        margin-top: 20px;
        margin-bottom: 12px;
        display: flex;
        align-items: center;

        p {
          padding: 5px 10px;
          margin: 0px 10px;
          border-radius: 3px;
          color: #6698ff;
          background-color: rgba(102, 152, 255, 0.2);
          font-size: 14px;
        }
      }
    }
  }
}
</style>